package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.domain.entity.User;
import cn.com.dcsgo.mapper.UserMapper;
import cn.com.dcsgo.service.UserService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * UserServiceImpl
 *
 * @author Dcsgo
 * @since 2025/4/3 10:30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public User getUserByPhone(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public User getUserByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return baseMapper.selectOne(wrapper);
    }

    @SentinelResource(value = "getUserByUsername", blockHandler = "getUserByUsernameBlockHandler")
    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * getUserByUsernameBlockHandler
     *
     * @param username username
     * @param e        BlockException 参数列表中的必须项
     * @return 未知用户
     */
    public User getUserByUsernameBlockHandler(String username, BlockException e) {
        return new User().setUsername("未知用户");
    }

    @Override
    public boolean hasUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return baseMapper.selectCount(wrapper) >= 1;
    }

    @Override
    public boolean hasPhone(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return baseMapper.selectCount(wrapper) >= 1;
    }

    @Override
    public boolean hasEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return baseMapper.selectCount(wrapper) >= 1;
    }
}
